import { Module } from 'vuex'
import { IRootState } from '../types'
import { ICompilerState } from './types'
import { IDataType } from '@/render/service/types'
import {
  getAllCompilers,
  updateCompiler,
  addCompilers,
  deleteCompiler
} from '@/render/service/compilers/compilers'
import { ICompiler } from '../baseconfig/types'

const compilersModule: Module<ICompilerState, IRootState> = {
  namespaced: true,
  state() {
    return {
      compilers: []
    }
  },
  getters: {
    getAllCompilers: (state) => {
      return state.compilers
    }
  },
  mutations: {
    SET_ALL_COMPILERS(state, val) {
      state.compilers = val
    },
    ADD_COMPILER(state, val) {
      if (state.compilers == null) {
        state.compilers = []
      }
      state.compilers.push(val)
    },
    DELETE_COMPILER(state, val) {
      if (state.compilers == null) {
        // 出错
      }
      const index = state.compilers.findIndex((item) => item.name === val)
      if (index === -1) {
        // 出错
      } else {
        state.compilers.splice(index, 1)
      }
    },
    UPDATE_COMPILER(state, val) {
      const index = state.compilers.findIndex(
        (item: ICompiler) => item.name === val.name
      )
      if (index === -1) {
        // 出错
      } else {
        state.compilers[index] = val
      }
    }
  },
  actions: {
    loadCompilers({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.compilers.length > 0) {
          resolve(state.compilers)
        } else {
          getAllCompilers()
            .then((res: IDataType) => {
              const compilers = res.data
              commit('param', 5)
              resolve(compilers)
            })
            .catch((error: any) => {
              console.log(error)
            })
        }
      })
    },
    updateCompiler({ commit, state }, compiler) {
      console.log(`修改 ${compiler.name} 编译器信息`)
      return new Promise((resolve, reject) => {
        updateCompiler(compiler).then((res: IDataType) => {
          commit('UPDATE_COMPILER', res.data)
          resolve(res.data)
        })
      })
    },
    addCompiler({ commit, state }, compiler) {
      console.log(`新增 ${compiler.name} 编译器信息`)
      return new Promise((resolve, reject) => {
        addCompilers(compiler).then((res: IDataType) => {
          commit('ADD_COMPILER', res.data)
          resolve(res.data)
        })
      })
    },
    deleteCompiler({ commit, state }, compiler) {
      console.log(`删除 ${compiler.name} 编译器信息`)
      return new Promise((resolve, reject) => {
        deleteCompiler(compiler.name).then((res: IDataType) => {
          commit('DELETE_COMPILER', compiler.name)
          resolve(res)
        })
      })
    }
  }
}

export default compilersModule
